
import pandas as pd
import random

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import imaplib
from selenium.webdriver.chrome.service import Service
# 读取邮箱地址
def read_emails_from_excel(file_path):
    df = pd.read_excel(file_path)
    emails = df['Email'].tolist()
    print(emails)
    return emails

# 获取邮箱密码
def read_passWords_from_excel(file_path):
    df = pd.read_excel(file_path)
    passwords = df['PassWord'].tolist()
    print(passwords)
    return passwords

# 获取网站用户名，同时也是网站密码
def read__emailUserNames_from_excel(file_path):
    df = pd.read_excel(file_path)
    emailUserNames = df['UserName'].tolist()
    print(emailUserNames)
    return emailUserNames

# 从邮箱中获取验证码
def get_verification_code(email_address, password):
    try:
        # 实现邮箱登录
        mail_server = 'imap.gmail.com'
        mail = imaplib.IMAP4_SSL(mail_server)
        time.sleep(2)
        mail.login(email_address, password)
        mail.select('inbox')
        time.sleep(2)
        result, data = mail.search(None, 'ALL')
        time.sleep(2)
        latest_email_id = data[0].split()[-1]
        result, email_data = mail.fetch(latest_email_id, '(RFC822)')
        raw_email = email_data[0][1].decode("utf-8")

        # 实现获取验证码
        # 清洗 MIME 编码
        cleaned_email = raw_email.replace("=3D", "=").replace("=C2=A0", " ").replace("=\r\n", "")

        # 使用 BeautifulSoup 解析
        from bs4 import BeautifulSoup
        soup = BeautifulSoup(cleaned_email, 'html.parser')
        code_element = soup.find('strong', class_='auth-code')

        # 获取到验证码成功
        if code_element:
            verification_code = code_element.get_text(strip=True)
            print(f"Found verification code: {verification_code}")
            return verification_code
        # 获取验证码错误
        else:
            print("Verification code not found in email body.")
            return None
    # 发生错误
    except Exception as e:
        print(f"Error retrieving verification code: {e}")
        return None

# 自动化注册流程
def register_user(email, password, username, driver):
    try:
        # 需要实现自动化流程网页
        driver.get("https://triple.global/zh-CN/auth-web/email-join")

        # 输入邮箱
        email_field = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "email"))
        )
        email_field.send_keys(email)

        # 提交邮箱
        send_email_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[text()='发送验证信至电子邮箱']"))
        )
        send_email_button.click()

        # 获取验证码
        time.sleep(20)
        print("开始找验证码")
        verification_code = get_verification_code(email, password)
        if not verification_code:
            raise Exception("Failed to retrieve verification code.")
        print("找到验证码")

        # 输入验证码 <input id="authCode" name="authCode" type="text" inputmode="numeric" placeholder="请输入6位验证码" class="sc-2d124b7-4 khgZXo">实现验证码体现
        code_field = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "authCode"))
        )
        code_field.send_keys(verification_code)

        # 提交验证码
        verify_button = driver.find_element(By.XPATH, "//button[contains(text(), '完成电子邮箱验证')]")
        verify_button.click()

        # 输密码
        password_field = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "password"))
        )
        password_field.send_keys(username)

        # 确认密码
        confirm_password_field = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "confirmPassword"))
        )
        confirm_password_field.send_keys(username)

        # 点击确定按钮
        confirm_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button.sc-65492d3d-1.iZkaFI"))
        )
        confirm_button.click()


        # 勾选授权
        agree_all_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='同意全部条款']]"))
        )
        agree_all_button.click()

        time.sleep(2)

        # 点击了agree_all_button才能点击，点击“确定”按钮
        print("开始勾选授权 “确定” 按钮")
        agree_all_button1 = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button.sc-7400dc49-8.bWAitu"))
        )
        agree_all_button1.click()
        print("结束勾选授权 “确定” 按钮")

        # 输入用户名
        name_file = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "name"))
        )
        name_file.send_keys(username)

        # 用户名确定按钮
        name_button = WebDriverWait(driver, 10).until(
            # sc-c967a17e-1 dVyBlm
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button.sc-c967a17e-1.dVyBlm"))
        )
        name_button.click()

        # 等待注册完成
        time.sleep(5)
        print("注册完成")
    except Exception as e:
        print(f"Error during registration: {e}")

if __name__ == "__main__":
    excel_file_path = r'D:\ProJect\tripleEmail\emails.xlsx'  # 替换为你的Excel文件路径

    # 获取需要的数据
    emails = read_emails_from_excel(excel_file_path)
    password = read_passWords_from_excel(excel_file_path)
    username = read__emailUserNames_from_excel(excel_file_path)

    # 设置WebDriver（这里以Chrome为例）
    service = Service(executable_path=r'D:\ProJect\tripleEmail\chromedriver-win64\chromedriver-win64\chromedriver.exe')

    # 打开浏览器实现控制
    driver = webdriver.Chrome(service=service)

    # 一行数据实现一次注册
    for i in range(len(emails)):
        print(i)
        register_user(emails[i], password[i], username[i], driver)

    driver.quit()

